<?php
/**
 * @package Joomla
 * @subpackage Jmonoslideshow
 * @copyright (C) 2010 - Matthieu BARBE - www.ccomca.com
 * @license GNU/GPL v2
 * 
 * Jmonoslideshow is a Joomla extension for Monoslideshow.
 *
 * Jmonoslideshow uses :
 * Monoslideshow (http://www.monoslideshow.com/)
 * Plupload (http://www.plupload.com/) by Moxicode Systems
 * json class by Michal Migurski, Matt Knapp, Brett Stimmerman
 * jquery a JavaScript Library (http://jquery.com/)
 * getid3 library (http://getid3.sourceforge.net/)
 * swfobject is an easy-to-use and standards-friendly method to embed Flash content, which utilizes one small JavaScript file (http://code.google.com/p/swfobject/)
 * Chained Selects jQuery Plugin (http://www.appelsiini.net/2010/jquery-chained-selects)
 *
 * Jmonoslideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );


// import Joomla modeladmin library
jimport('joomla.application.component.modeladmin');

/**
 * Model Model
 *
 * @package    Jmonoslideshow
 * @subpackage Models
 */
class JmonoslideshowModelMedia extends JModelAdmin
{

	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.6
	 */
	protected $text_prefix = 'COM_JMONOSLIDESHOW';


	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param	object	A record object.
	 * @return	boolean	True if allowed to delete the record. Defaults to the permission set in the component.
	 * @since	1.6
	 */
	protected function canDelete($record)
	{
		if (!empty($record->id)) {
			if ($record->state != -2) {
				return ;
			}
			$user = JFactory::getUser();

			
		}
	}
	
	protected function canEditState($record) 
	{
		$user = JFactory::getUser();

		// Check against the category.
		if (!empty($record->id)) 
		{
			return $user->authorise('core.edit.state', 'com_jmonoslideshow.model.' . (int)$record->id);
		}

		// Default to component settings if category not known.
		else 
		{
			return parent::canEditState($record);
		}
	}
	
	
	
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'Media', $prefix = 'JmonoslideshowTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		An optional array of data for the form to interogate.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	JForm	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{

		// Get the form.
		$form = $this->loadForm('com_jmonoslideshow.model', 'media', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		//$data = JFactory::getApplication()->getUserState('com_jmonoslideshow.edit.model.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		
			
		}
		
		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param	integer	The id of the primary key.
	 *
	 * @return	mixed	Object on success, false on failure.
	 * @since	1.6
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk)) {
			
			// Get the database object
		$db = JFactory::getDbo();

		// Get the tags
		$query = $db->getQuery(true);
		$query->select('name');
		$query->from($db->nameQuote('#__monoslideshow_tag'));
		$query->where('id=' . (int)$item->id);
		$query->order('name');
		$db->setQuery($query);
		$item->tags = $db->loadResultArray();
		if ($db->getErrorNum()) 
			{
			$this->setError($db->getErrorMsg());
			return false;
			}
			
		// Get categories
		$query = $db->getQuery(true);
		$query->select('category_id');
		$query->from($db->nameQuote('#__monoslideshow_media_category'));
		$query->where('media_id=' . (int)$item->id);
		$query->order('category_id');
		$db->setQuery($query);
		$item->catid = $db->loadResultArray();
		if ($db->getErrorNum()) 
			{
			$this->setError($db->getErrorMsg());
			return false;
			}
			
		}

		return $item;
	}

	
	/**
	 * Method to move a media
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkMedia($cid)
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT c.*, COUNT( m.id ) AS total'
		. ' FROM #__monoslideshow_category AS c'
		. ' LEFT JOIN #__monoslideshow AS m ON m.albumid = c.id'
		. ' WHERE c.id = '.$cid.' '
		. ' GROUP BY c.id'
		;
		$db->setQuery( $query );

		if (!($rows = $db->loadObjectList())) {
			JError::raiseError( 500, $db->stderr() );
			return false;
		}
		
		foreach ($rows as $row) {
			if ($row->total == 0) return true; else return false;
		}
	}
	
	
	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @since	1.6
	 */
	protected function prepareTable(&$table)
	{
		jimport('joomla.filter.output');
		$date = JFactory::getDate();
		$user = JFactory::getUser();

		$table->title		= htmlspecialchars_decode($table->title, ENT_QUOTES);
		

		if (empty($table->id)) {
			// Set the values

			// Set ordering to the last item if not set
			if (empty($table->ordering)) {
				$db = JFactory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__monoslideshow');
				$max = $db->loadResult();

				$table->ordering = $max+1;
			}
		}
		else {
			// Set the values
		}
	}
	
	
	
	
	/**
	 * Method to save the form data.
	 *
	 * @param	array	$data	The form data.
	 *
	 * @return	boolean	True on success.
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelAdmin::save
	 */
	public function save($data) 
	{
		$id = $data['id'];
		
		// Compte the is_new and the change_language flags
		if ($id) 
		{
			$table = $this->getTable();
			$table->load($id);
			$is_new = false;
		}
		else
		{
			$is_new = true;
		}

		// If saving is successfull
		if (parent::save($data)) 
		{
			$db = JFactory::getDbo();
			if ($is_new) 
			{
				// Get the new inserted id
				$id = $this->getState('media.id');
				
				//add multiple categories
				$insert = array();
				foreach ($data[catid] as $key => $value)
				{
					$insert[]='('.$value.','.$id.','.$id.')';
				}
				$query = "INSERT INTO ".$db->nameQuote('#__monoslideshow_media_category')." (category_id,media_id,ordering) VALUES ".implode(',',$insert)."";
				$db->setQuery($query);
				$db->query();
				if ($db->getErrorNum()) 
				{
					$this->setError($db->getErrorMsg());
					return false;
				}
				
				
			}
			else
			{
				// Get the current id
				$id = $table->id;
				
				//add multiple categories
				$query = "SELECT category_id FROM ".$db->nameQuote('#__monoslideshow_media_category')." WHERE media_id = ".(int) $id;
				$db->setQuery($query);
				$olds = $db->loadResultArray();
				$do_nothing = array_intersect($data[catid],$olds);
				$delete = array_diff($olds,$do_nothing);
				$news = array_diff($data[catid],$do_nothing);
				
				if(!empty($delete)){
					$db->setQuery('DELETE FROM '.$db->nameQuote('#__monoslideshow_media_category').' WHERE media_id='.$id.' AND category_id IN ('.implode(',',$delete).')');
					$db->query();
				}
				if(!empty($news)){
					$insert = array();
					foreach($news as $new){
						$insert[]='('.$new.','.$id.')';
					}
					$query = 'INSERT IGNORE INTO '.$db->nameQuote('#__monoslideshow_media_category').' (category_id,media_id) VALUES '.implode(',',$insert).';';
					$db->setQuery($query);
					$db->query();
				}

				// delete old item tags
				$query = "DELETE FROM ".$db->nameQuote('#__monoslideshow_tag')." WHERE id = ".(int) $id;
				$db->setQuery($query);
				$db->query();	
				if ($db->getErrorNum()) 
				{
					$this->setError($db->getErrorMsg());
					return false;
				}
			}

			$tags = explode("," , JRequest::getVar( 'tags', '' , 'POST' ));
		
			foreach ($tags as $key => $value)
			{
				if ($value)
					{
					$query = "INSERT INTO ".$db->nameQuote('#__monoslideshow_tag')." VALUES (".(int)$id.", ".$db->quote($value)." )";
					$db->setQuery($query);
					$db->query();
					}
			}
			
			
			
			
			return true;
		}
		return false;
	}
	  
	  
	public function delete(&$pks)
	{
		$pks	= (array) $pks;
		$table	= $this->getTable();
		// Iterate the items to delete each one.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk)) {

					$searchpath = JPATH_SITE . DS . "media". DS ."com_jmonoslideshow". DS ."upload";
					if ($table->filename)
						{
							$files = JFolder::files($searchpath, $table->filename, true, true);
							
							foreach ($files as $file) {
								   if (!JFile::delete($file)) return false;
							}
						}
					
					$db = JFactory::getDbo();
					$query = "DELETE FROM  ".$db->nameQuote('#__monoslideshow_media_category')." WHERE media_id = ".(int)$table->id;
					$db->setQuery($query);
					$db->query();
					if ($db->getErrorNum()) 
						{
							$this->setError($db->getErrorMsg());
							return false;
						}
					
					if (!$table->delete($pk)) {
						$this->setError($table->getError());
						return false;
					}	
					
			}
			else {
				$this->setError($table->getError());
				return false;
			}
		
		}
		return true;
		
	}
	
	public function reorder (&$pks, &$delta)
	{
		$app = &JFactory::getApplication();
		$option = JRequest::getVar('option');
		$categoryId = $app->getUserStateFromRequest($option . '.filter.catid', 'filter_catid');
		$categoryId	= $categoryId ? $categoryId[0] : '';
		
		if ($categoryId != "")
			{
			$db = JFactory::getDbo();
				foreach ($pks as $i => $pk)
				{
					$query = "SELECT category_id FROM ".$db->nameQuote('#__monoslideshow_media_category')." WHERE media_id = ".(int) $pk." AND category_id = ".(int) $categoryId;
					$db->setQuery($query);
					$olds = $db->loadResultArray();
				}
				
			}
			else
			{
				return false;
			}
		return true;
	}
	
	function move($direction)
	{
		$row =& $this->getTable('');
		if (!$row->load($this->_id)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move( $direction, ' id = '.(int) $row->id.' AND published >= 0 ' )) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}
	

}// class